﻿$(document).ready(function () {
    $('input[type=file]').bootstrapFileInput();
    $('.file-inputs').bootstrapFileInput();
    $("#newAppointment").click(function () {
        $.ajax({
            type: "POST",
            url: _AbsolutePath + 'Appointment/NewDocAppt',
            contentType: "application/json",
            data: null,
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                location.href = _AbsolutePath + 'Appointment/EditAppointment';
            },
            error: function (xhr) {
            }
        });
    });
    $("#savePatientDetails").click(function () {
        var patient = {};
        patient.Id = patientId;
        patient.Name = $("#patientName").val();
        patient.Email = $("#emailId").val();
        patient.Phone = $("#bookDetailPhone").val();
        var dateOfBirth = $("#dateOfBirth").val().split('/');
        patient.DOB = new Date(dateOfBirth[2], dateOfBirth[1] - 1, dateOfBirth[0]);
        patient.Gender = {};
        patient.Gender.Id = $("#chkGender:checked").length > 0 ? 1 : 2;
        $.ajax({
            type: "POST",
            url: _AbsolutePath + 'Patient/SavePatientDetails',
            contentType: "application/json",
            data: JSON.stringify({ patient: patient }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                if (res > 0) {
                    SendEmailtoDoctor(patientId);
                    alert("Personal details has been saved");
                }
                return false;
            },
            error: function (xhr) {
            }
        });
    });
    $("#btnAddImages").click(function () { location.href = "/Appointment/CaptureImages"; });

    $('input:checkbox').bootstrapSwitch();
    $("#slotTiming").combobox();

    //$('#patientSearch').typeahead({
    //    source: function (query, process) {
    //        var $items = new Array;
    //        $items = [""];
    //        $.ajax({
    //            type: "POST",
    //            url: _AbsolutePath + 'Patient/GetPatientName',
    //            contentType: "application/json",
    //            data: JSON.stringify({ PatientName: query }),
    //            dataType: "json",
    //            success: function (data) {
    //                console.log(data);
    //                $.map(data, function (data) {
    //                    var group;
    //                    group = {
    //                        id: data.Id,
    //                        name: data.Name + " ( " + data.Phone + ", " + data.Email + " ) ",
    //                        toString: function () {
    //                            return JSON.stringify(this);
    //                            //return this.app;
    //                        },
    //                        toLowerCase: function () {
    //                            return this.name.toLowerCase();
    //                        },
    //                        indexOf: function (string) {
    //                            return String.prototype.indexOf.apply(this.name, arguments);
    //                        },
    //                        replace: function (string) {
    //                            var value = '';
    //                            value += this.name;
    //                            if (typeof (this.level) != 'undefined') {
    //                                value += ' <span class="pull-right muted">';
    //                                value += this.level;
    //                                value += '</span>';
    //                            }
    //                            return value;
    //                        }
    //                    };
    //                    $items.push(group);
    //                });

    //                process($items);
    //            }
    //        });
    //    },
    //    property: 'name',
    //    items: 10,
    //    minLength: 1,
    //    updater: function (item) {
    //        var item = JSON.parse(item);
    //        console.log(item.name);
    //        $('#SelectedPatient').val(item.id);
    //        SetPatientSession(item.id);
    //        return item.name;
    //    }
    //});

    $("#dateOfBirth").change(function () {
        var dateOfBirth = $(this).val().split('/');
        var dobYear = dateOfBirth.length ? new Date(dateOfBirth[2], dateOfBirth[1] - 1, dateOfBirth[0]).getYear() : new Date();
        var currentYear = new Date().getYear();
        $("#age").val(((currentYear - dobYear) >= 0 ? currentYear - dobYear : 0) + 'yr');
    });
    $("#dateOfBirth").trigger("change");
    if (prevAppt != null && prevAppt != "") {
        for (var i = 0; i < prevAppt.length; i++) {
            GetImageList(prevAppt[i].Id);
        }
    }
    if (futureAppt != null && futureAppt != "") {
        for (var i = 0; i < futureAppt.length; i++) {
            GetImageList(futureAppt[i].Id);
        }
    }
    GetImageList(patientId);
});
function GetImageList(Id) {
    $.ajax({
        async: true,
        type: "POST",
        url: _AbsolutePath + 'Appointment/GetImageListForPatient',
        contentType: "application/json",
        data: JSON.stringify({ DocApptId: Id }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            var isImageGenerated = false;
            if (res != null && res.length > 0) {
                for (var i = 0; i < res.length; i++) {
                    if (res[i].ImagePath != null && res[i].ImagePath != "") {
                        if (res[i].isImage == true) {
                            $("#" + Id).append("<li styl='width:100'><a class='fancybox'  rel='group' href=" + res[i].ImagePath + "><img src=" + res[i].ThumbnailPath + " alt='' /></a></li>");
                        } else {
                            $("#" + Id).append("<li styl='width:100'><a class='fancybox'  rel='group' href=" + res[i].ImagePath + "><img src=" + _AbsolutePath + "/" + res[i].ThumbnailPath + " /></a></li>");
                        }
                        
                        isImageGenerated = true;
                    } else {
                        GeneratePresciptionDiv(res[i].Prescription, res[i]._PrescriptionTime, "divPrescription_" + Id, i);
                    }
                }
                if (isImageGenerated == true) {
                    $($("#" + Id).find(".fancybox")).fancybox();
                    $("#" + Id).bxSlider({
                        minSlides: 2,
                        maxSlides: 10,
                        slideWidth: 250,
                        slideMargin: 5,
                        infiniteLoop: true
                    });
                }
            }
        },
        error: function (xhr) {
        }
    });
}


function GetPatientInfo(PatId) {
    $.ajax({
        async: true,
        type: "POST",
        url: _AbsolutePath + 'Patient/GetPatientById',
        contentType: "application/json",
        data: JSON.stringify({ PatientId: PatId }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            if (res != null) {
                $("#bookDetailPhone").val(res.Patient.Phone);
                $("#bookDetailPurpose").val(res.Purpose);
                if (res.FollowUpStatus == true) $("#chkFollowup").bootstrapSwitch('state', true, true);
                $("#emailId").val(res.Patient.Email);
                $("#patientDetailPhone").val(res.Patient.Phone);
                $("#age").val((new Date(parseInt(res.Patient.DOB.replace("/Date(", "").replace(")/", "")))).getDate().toString());
                if (res.Patient.Gender.Id == 1)
                    $('#chkGender').bootstrapSwitch('state', true, true);
                $("#newDocApptId").val(res.Id);
                appointmentDoctorObject = res
                appointmentDoctorObject.Id = $("#DocApptId").val();
                GetImageList();
                //  if (res.Patient.Gender.Id == 1) $("#chkGender").prop('checked', true);
            }
        },
        error: function (xhr) {
        }
    });
}
function SendEmailtoDoctor(patientId) {
    $.ajax({
        async: true,
        type: "POST",
        url: _AbsolutePath + 'Appointment/SendEmailOnPatientProfileUpdate',
        contentType: "application/json",
        data: JSON.stringify({ patientId: patientId }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {

        },
        error: function (xhr) {
        }
    });
}
